package com.krtech.wecard.module.ramble.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.ramble.entity.RambleDrawChance;
import com.krtech.wecard.module.ramble.entity.RambleShareLog;
import com.krtech.wecard.module.ramble.enums.RambleEnums;
import com.krtech.wecard.module.ramble.service.*;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.krtech.wecard.module.ramble.mapper.RambleLoginLogMapper;
import com.krtech.wecard.module.ramble.entity.RambleLoginLog;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RambleLoginLogServiceImpl extends ServiceImpl<RambleLoginLogMapper, RambleLoginLog> implements RambleLoginLogService {


    @Autowired
    private RambleDrawChanceService chanceService;

    @Autowired
    private RambleShareLogService shareLogService;

    @Autowired
    private SysKeyValueService keyValueService;

    @Autowired
    private RambleHexiaoLogService hexiaoLogService;

    @Autowired
    private RambleLeaderboardService leaderboardService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean loginLog(RambleLoginLog loginLog) {

        SysUser userInfo = LoginUtil.getUserInfo();
        if (userInfo == null || StrUtil.isEmpty(userInfo.getMipOpenId())){
            throw new BusinessException("当前用户异常，请联系管理员");
        }

        if (loginLog.getStepNumber() == null){
            throw new BusinessException("必填参数stepNumber不能为空");
        }
        //判断当前有没有，如果没有，则添加
        RambleLoginLog currentRamble = this.getOne(new QueryWrapper<RambleLoginLog>()
                .eq(RambleLoginLog.COL_PHONE, userInfo.getPhone()).eq(RambleLoginLog.COL_RIGISTER_DATE, DateUtil.today()));

        if (currentRamble == null){
            loginLog.setCreatedTime(new Date());
            loginLog.setNickName(userInfo.getNickName());
            loginLog.setOpenId(userInfo.getMipOpenId());
            loginLog.setPhone(userInfo.getPhone());
            loginLog.setRigisterDate(new Date());

            generateDrawChance();

            return this.save(loginLog);
        }

        currentRamble.setStepNumber(loginLog.getStepNumber());
        this.updateById(currentRamble);

        //查询当前这个人的步数并进行更新这个人的抽奖次数

        generateDrawChance();

        //优化排行榜
        leaderboardService.analyze(userInfo.getPhone());

        return true;
    }

    @Override
    public void generateDrawChance(){
        SysUser userInfo = LoginUtil.getUserInfo();
        //查询环境变量
        SysKeyValue stepKeyValue = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, RambleEnums.STEP));

        if (stepKeyValue == null){
            throw new BusinessException("环境变量step未配置，请联系管理员");
        }

        int step = Integer.parseInt(stepKeyValue.getSysValue());

        RambleDrawChance drawChance = chanceService.getOne(new QueryWrapper<RambleDrawChance>()
                .eq(RambleDrawChance.COL_PHONE, userInfo.getPhone()));

        if (drawChance == null){
            RambleDrawChance newDrawChance = new RambleDrawChance();
            newDrawChance.setCreatedTime(new Date());
            newDrawChance.setNickName(userInfo.getNickName());
            newDrawChance.setPhone(userInfo.getPhone());
            newDrawChance.setOpenId(userInfo.getMipOpenId());
            //计算中奖次数
            List<RambleLoginLog> rambleLoginLogList = this.list(new QueryWrapper<RambleLoginLog>()
                    .eq(RambleLoginLog.COL_PHONE, userInfo.getPhone()));


            int stepSum = 0;
            if (rambleLoginLogList.size() > 0){
                stepSum = rambleLoginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
            }
            int chance = stepSum / step;
            // 还要考虑到分享次数
            int shareCount = shareLogService.count(new QueryWrapper<RambleShareLog>()
                    .eq(RambleShareLog.COL_SHARER_PHONE, userInfo.getPhone()));

            int totalChance = chance + shareCount;
            newDrawChance.setDrawChance(totalChance);

            chanceService.save(newDrawChance);

            // 生成核销码
            hexiaoLogService.getHexiaoCode(newDrawChance.getId());
        }else {
            //计算中奖次数
            List<RambleLoginLog> rambleLoginLogList = this.list(new QueryWrapper<RambleLoginLog>()
                    .eq(RambleLoginLog.COL_PHONE, userInfo.getPhone()));

            int stepSum = 0;
            if (rambleLoginLogList.size() > 0){
                stepSum = rambleLoginLogList.stream().mapToInt(RambleLoginLog::getStepNumber).sum();
            }
            int chance = stepSum / step;
            // 还要考虑到分享次数
            int shareCount = shareLogService.count(new QueryWrapper<RambleShareLog>()
                    .eq(RambleShareLog.COL_SHARER_PHONE, userInfo.getPhone()));

            int totalChance = chance + shareCount;
            drawChance.setDrawChance(totalChance);
            chanceService.updateById(drawChance);
        }
    }
}



